﻿var CererePage = function(pageContainer) {

    CererePage.superclass.constructor.call(this, pageContainer);

    this.ModuleCode = "TM_04";

    var buttonActions = {
        Save: 0,
        Accept: 1,
        Cancel: 2,
        Revoke: 3,
        AcceptRevoke: 4,
        SaveCancel: 5,
        ModifyCancel: 6,
        None: 7
    };

    var actionFirstBtn = null;
    var actionSecondBtn = null;

    var self = this;
    var cerere = null;

    var soldCO = -1;
    var current_pra_id = -1;
    var tipConcediu = null;
    var dataStart = null;
    var dataSfarsit = null;
    var dataCurenta = null;
    var centruCost = null;
    var isModified = false;
    var dataWasSet = false;
    var oraStart = null;
    var oraSfarsit = null;
    var pra_id_inlocuitor = null;

    this.Actions = [
        {
            Text: 'Istoric cerere',
            Callback: function() { showIstoricCerere(); },
            CanExecute: function() { return cerere != null; },
            ImageUrl: getImageUrl('content_history.png')
        },
        {
            Text: 'Stergere cerere',
            Callback: function() { stergereCerere(); },
            CanExecute: function() { return self.Rights.Stergere; },
            ImageUrl: getImageUrl('content_delete.png')
        }
    ];

    this.Rights = {
        Modificare: true,
        SchimbarePersoana: true,
        SchimbareTipConcediu: true,
        SchimbareDataStart: true,
        SchimbareDataSfarsit: true,
        SchimbareCentruCost: true,
        SchimbareInlocuitor: true,
        IncarcareFisier: true,
        Aprobare: true,
        Refuzare: true,
        Stergere: true
    };

    var Elements = {
        content: pageContainer.find('.content:first'),
        angajatContainer: pageContainer.find('.angajatContainer'),
        changeEmployeePic: pageContainer.find('.changeEmployee'),
        selectTipCerere: pageContainer.find('.selectTipCerere'),
        titleSoldCO: pageContainer.find(".titleSoldCO"),
        soldCO: pageContainer.find('.soldCO'),
        dataStart: pageContainer.find('.dataStart'),
        dataSfarsit: pageContainer.find('.dataSfarsit'),
        dataStartInput: pageContainer.find('.dataStartInput'),
        dataSfarsitInput: pageContainer.find('.dataSfarsitInput'),
        totalZile: pageContainer.find(".totalZile"),
        nrZileCalendaristiceValue: pageContainer.find('.nrZileCalendaristiceValue'),
        nrZileCalendaristice: pageContainer.find('.nrZileCalendaristice'),
        nrZileLucratoareValue: pageContainer.find('.nrZileLucratoareValue'),
        nrZileLucratoare: pageContainer.find('.nrZileLucratoare'),
        totalZileContainer: pageContainer.find('.totalZileContainer'),
        descriereCerereTextArea: pageContainer.find('.descriereCerereTextArea'),
        motivRefuzDialog: pageContainer.find('.motivRefuzDialog'),
        motivModificareDialog: pageContainer.find('.motivModificareDialog'),
        titleCentruCost: pageContainer.find('.titleCentruCost'),
        centruCost: pageContainer.find('.centruCost'),
        firstBtn: pageContainer.find(".first-btn"),
        secondBtn: pageContainer.find(".second-btn"),
        getPozaDocument: pageContainer.find(".getPozaDocument"),
        status: pageContainer.find('.status'),
        fisiereContainer: pageContainer.find('.fisiereContainer'),
        atasareDocument: pageContainer.find('.atasareDocument'),
        motivRefuzText: pageContainer.find('.motivRefuzText'),
        motivRefuz: pageContainer.find('.motivRefuz'),
        totalOreContainer: pageContainer.find('.totalOreContainer'),
        dataCurentaInput: pageContainer.find('.dataCurentaInput'),
        dataCurenta: pageContainer.find('.dataCurenta'),
        oraStartInput: pageContainer.find('.oraStartInput'),
        oraStart: pageContainer.find('.oraStart'),
        oraSfarsitInput: pageContainer.find('.oraSfarsitInput'),
        oraSfarsit: pageContainer.find('.oraSfarsit'),
        replacementEmployeeSection: pageContainer.find('.replacementEmployeeSection'),
        replacementEmployeeName: pageContainer.find('.replacementEmployeeSection .replacementEmployeeName')
    };

    var Templates = {
        userInfoTemplate: pageContainer.find(".userInfoTemplate"),
        userInfoTemplateCompiled: null,
        fisierCerereTemplateCompiled: null,

        refuzMotivTemplate: pageContainer.find("#refuzMotivTemplate"),
        modificareMotivTemplate: pageContainer.find("#modificareMotivTemplate"),
        fisierCerereTemplate: pageContainer.find('#fisierCerereTemplate')
    };

    this.setCerere = function(ccd_id, pra_id) {
        Elements.content.hide();
        isModified = false;
        app.Phone.setModuleAction(ModuleActions.None);
        if (ccd_id) {
            app.Phone.setPageTitle(translate('Module_Title_VizualizareCerere'));
            dataWasSet = false;
            if (!cerere || cerere.CCD_ID != ccd_id)
                Elements.content.hide();
            if (!cerere)
                app.showLoadingScreen();
            app.TMMService.TMM.GetCerereConcediu(ccd_id, function(response) {
                app.hideLoadingScreen();
                if (response.Exception)
                    return app.MessagesFactory.showToastWarning(translate('General_Eroare'), translate('General_EroareServer'));

                app.Phone.setModuleAction(ModuleActions.More);
                setCerereData(response.FinalResult);
                Elements.content.show();
            });
        } else {
            dataWasSet = true;
            centruCost = null;
            cerere = null;
            setRights();
            current_pra_id = pra_id || -1;
            self.setTipConcediu(null);
            setDataStart(null);
            setDataSfarsit(null);
            setReplacementEmployee(null);
            loadUserInfo(current_pra_id);
            Elements.motivRefuz.parent().hide();
        }
    };

    this.setModified = function(modified) {
        isModified = modified;
    };

    var setRights = function() {
        if (!cerere) {
            self.Rights.Modificare = true;
            self.Rights.SchimbarePersoana = !app.LastPage || !app.LastPage.instance || (app.LastPage.instance != app.Pages.Dashboard.instance);
            self.Rights.SchimbareTipConcediu = true;
            self.Rights.SchimbareDataStart = true;
            self.Rights.SchimbareDataSfarsit = true;
            self.Rights.SchimbareCentruCost = true;
            self.Rights.IncarcareFisier = true;
            self.Rights.Aprobare = false;
            self.Rights.Refuzare = false;
            self.Rights.Stergere = false;
            self.Rights.SchimbareInlocuitor = true;
        } else {
            self.Rights.Modificare = cerere.Status <= 1 && cerere.PoateModifica >= 1 && (app.User.Rights.ModificareCereriConcedii || app.User.Rights.ALL) && hasRight(Constants.Authentication.Rights.ModificareCereriConcedii, cerere.Roles);
            self.Rights.SchimbarePersoana = false;
            self.Rights.SchimbareTipConcediu = self.Rights.Modificare && cerere.PoateModifica == 2;
            self.Rights.SchimbareDataStart = self.Rights.Modificare && cerere.PoateModifica == 2;
            self.Rights.SchimbareDataSfarsit = self.Rights.Modificare;
            self.Rights.SchimbareCentruCost = self.Rights.Modificare;
            self.Rights.IncarcareFisier = self.Rights.Modificare;
            self.Rights.Aprobare = cerere.Status == 0 && (app.User.Rights.AprobareCereriConcedii || app.User.Rights.ALL) && hasRight(Constants.Authentication.Rights.AprobareCereriConcedii, cerere.Roles);
            self.Rights.Refuzare = cerere.Status <= 1 && (app.User.Rights.RefuzareCereriConcedii || app.User.Rights.ALL) && hasRight(Constants.Authentication.Rights.RefuzareCereriConcedii, cerere.Roles);
            self.Rights.Stergere = self.Rights.Modificare && cerere.PoateSterge && (app.User.Rights.StergereCereriConcedii || app.User.Rights.ALL) && hasRight(Constants.Authentication.Rights.StergereCereriConcedii, cerere.Roles);
            self.Rights.SchimbareInlocuitor = self.Rights.Modificare;
        }
    };

    var hasRight = function(rightToVerify, roles) {
        if (!rightToVerify || !roles)
            return false;

        for (var i = 0; i < roles.length; i++) {
            var r = roles[i];
            var userRole = app.User.getRoleByRoleType(r);
            if (userRole) {
                if (userRole.Rights) {
                    if ($.inArray(rightToVerify, userRole.Rights) || $.inArray(Constants.Authentication.Rights.ALL, userRole.Rights))
                        return true;
                }
            }
        }

        return false;
    };

    var setCerereData = function(c) {
        cerere = c;

        current_pra_id = cerere.PRA_ID;
        if (cerere.CC_ID) {
            centruCost = {
                CC_ID: cerere.CC_ID,
                CC_NUME: cerere.CC_NUME
            };
        } else centruCost = null;

        self.setTipConcediu({
            Tip: {
                ELM_ID: cerere.ELM_ID,
                TCO_ID: cerere.TCO_ID,
                Nume: cerere.TipConcediu,
                TIP_CC: cerere.TIP_CC,
                IsHour: cerere.ESTE_ORA,
                NeedsReplacementEmployee: cerere.ReplacementEmployee != null
            }
        }, true);

        if (cerere.STP_ID)
            tipConcediu.Subtip = {
                STP_ID: cerere.STP_ID,
                STP_NUME: cerere.TipConcediu
            };

        setRights();

        loadUserInfo(current_pra_id);

        if (cerere && cerere.CCD_ID) {
            if (!cerere.ESTE_ORA) {
                Elements.totalZileContainer.show();
                Elements.totalZileContainer.find('span:first').hide();
                Elements.totalZileContainer.find('span:eq(1)').show();

                Elements.nrZileLucratoareValue.html(c.NrZileLucratoare);
                if (c.NrZileLucratoare == 1)
                    Elements.nrZileLucratoare.html(translate('Cereri_ZiLucratoare'));
                else Elements.nrZileLucratoare.html(translate('Cereri_ZileLucratoare'));

                Elements.nrZileCalendaristiceValue.html(c.NrZileCalendaristice);
                if (c.NrZileCalendaristice == 1)
                    Elements.nrZileCalendaristice.html(translate('Cereri_ZiCalendaristica'));
                else Elements.nrZileCalendaristice.html(translate('Cereri_ZileCalendaristice'));
            }
        }
    };

    var loadUserInfo = function(pra_id) {
        current_pra_id = pra_id;

        renderEmployeeInfo(null, true);

        if (cerere && cerere.CCD_ID) {
            var employeeInfo = {
                HasPicture: cerere.ArePoza,
                Name: cerere.Nume,
                FNC_NUME: cerere.Functie,
                DPT_NUME: cerere.Departament,
                CNP: cerere.PRS_CNP,
                Marca: cerere.PRS_MARCA,
                PRS_ID: cerere.PRS_ID
            };
            renderEmployeeInfo(employeeInfo);

            Elements.titleSoldCO.parent().hide();

            self.setTipConcediu(tipConcediu);

            if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour) {
                setDataCurenta(cerere.DataStart);
                setOraStart(cerere.DataStart);
                setOraSfarsit(cerere.DataSfarsit);
                dataWasSet = true;
                updateNrZile();
            } else {
                setDataStart(cerere.DataStart);
                setDataSfarsit(cerere.DataSfarsit);
            }

            if (cerere.ReplacementEmployee)
                setReplacementEmployee(cerere.ReplacementEmployee);

            if (cerere.Descriere) {
                Elements.descriereCerereTextArea.show().val(cerere.Descriere);
                if (!self.Rights.Modificare)
                    Elements.descriereCerereTextArea.attr('disabled', 'disabled');
                else Elements.descriereCerereTextArea.removeAttr('disabled');
            } else Elements.descriereCerereTextArea.val('').hide();

            Elements.status.show();
            pageContainer.find('.statusText').parent().show();
            if (cerere.Status == 0)
                Elements.status.html(translate('Cerere_Status_Initiata'));
            else if (cerere.Status == 1)
                Elements.status.html(translate('Cerere_Status_Aprobata'));
            else if (cerere.Status == 2)
                Elements.status.html(translate('Cerere_Status_Refuzata'));
            else if (cerere.Status == 3)
                Elements.status.html(translate('Cerere_Status_Finalizata'));

            if (cerere.Status == 2 && cerere.RejectionReason) {
                Elements.motivRefuz.html(cerere.RejectionReason);
                Elements.motivRefuzText.parent().show();
            } else {
                Elements.motivRefuz.parent().hide();
            }

            if (self.Rights.Aprobare && self.Rights.Refuzare)
                setButtonsActions(buttonActions.AcceptRevoke);
            else setButtonsActions(buttonActions.None);

            if (self.Rights.Modificare)
                Elements.descriereCerereTextArea.show();

            isModified = false;

            if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour)
                if (!self.Rights.SchimbareDataStart && !self.Rights.SchimbareDataSfarsit)
                    Elements.dataCurenta.addClass('disabled');

            if (!self.Rights.SchimbareDataStart) {
                if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour) {
                    Elements.oraStart.addClass('disabled');
                } else Elements.dataStart.addClass('disabled');
            } else {
                if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour) {
                    Elements.oraStart.removeClass('disabled');
                } else Elements.dataStart.removeClass('disabled');
            }

            if (!self.Rights.SchimbareDataSfarsit) {
                if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour) {
                    Elements.oraSfarsit.addClass('disabled');
                } else Elements.dataSfarsit.addClass('disabled');
            } else {
                if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour) {
                    Elements.oraSfarsit.removeClass('disabled');
                } else
                    Elements.dataSfarsit.removeClass('disabled');
            }

            Elements.content.show();

            dataWasSet = true;
        } else {
            Elements.status.hide();
            pageContainer.find('.statusText').parent().hide();
            setButtonsActions(buttonActions.SaveCancel);
            Elements.titleSoldCO.parent().hide();
            Elements.descriereCerereTextArea.show().val('').removeAttr('disabled');
            Elements.totalZileContainer.show();
            Elements.dataStart.removeClass('disabled');
            Elements.dataSfarsit.removeClass('disabled');
            Elements.dataCurenta.removeClass('disabled');
            Elements.oraStart.removeClass('disabled');
            Elements.oraSfarsit.removeClass('disabled');

            if (pra_id && pra_id > 0) {
                app.TMMService.General.GetSubordinateInfo(pra_id, function(response) {
                    renderEmployeeInfo(response.FinalResult);
                    soldCO = -1;
                    showSoldCO();
                    updateNrZile();

                    Elements.content.show();
                });
            } else {
                if (app.User.IsAlsoEmployee)
                    app.TMMService.TMM.GetUserInfo(function(response) {
                        renderEmployeeInfo(response.FinalResult);
                        current_pra_id = response.FinalResult.PRA_ID;
                        soldCO = -1;
                        showSoldCO();
                        updateNrZile();

                        Elements.content.show();
                    });
                else {
                    updateNrZile();
                    renderEmployeeInfo(null);

                    Elements.content.show();
                }
            }
        }

        Elements.angajatContainer.unbind().click(function(e) {
            if (self.Rights.SchimbarePersoana)
                chooseEmployee();
            return Event.stopEvent(e);
        });

        showCentruCost();

        isModified = false;

        setFisiere();
    };

    var setFisiere = function() {
        if (self.Rights.IncarcareFisier)
            Elements.atasareDocument.show();
        else Elements.atasareDocument.hide();

        Elements.fisiereContainer.empty();
        if (!cerere)
            return Elements.getPozaDocument.html(translate('Cerere_NuAreAtasamente'));

        if (!Templates.fisierCerereTemplateCompiled) {
            var source = Templates.fisierCerereTemplate.html();
            Templates.fisierCerereTemplateCompiled = Handlebars.compile(source);
        }

        Handlebars.registerHelper('hasRightToDelete', function() {
            return self.Rights.IncarcareFisier;
        });

        var count = 0;
        var html = "";
        for (var i = 0; i < cerere.Documents.length; i++) {
            var d = cerere.Documents[i];
            if (d.Status != 2) {
                html += Templates.fisierCerereTemplateCompiled(d);
                count++;
            }
        }

        if (count) {
            Elements.getPozaDocument.html(translate('Cerere_AreAtasamente'));
            Elements.fisiereContainer.html(html);
        } else Elements.getPozaDocument.html(translate('Cerere_NuAreAtasamente'));
    };

    var showCentruCost = function() {
        if (app.TMMData.Setari.TipPontare == 1 && tipConcediu && tipConcediu.Tip.TIP_CC) {
            if (app.TMMData.Setari.TipCentruCost == 0)
                Elements.centruCost.html(translate('General_Selectati'));
            else Elements.centruCost.html(translate('General_Necompletat'));

            Elements.centruCost.show();
            Elements.titleCentruCost.show();

            if (cerere) {
                if (cerere.CC_ID) {
                    if (app.TMMData.Setari.TipCentruCost == 0)
                        Elements.centruCost.html(cerere.CC_NUME);
                    else Elements.centruCost.html(translate('General_Completat'));
                }

                if (!centruCost && !isModified) {
                    Elements.centruCost.hide();
                    Elements.titleCentruCost.hide();
                }
            }
        } else {
            Elements.titleCentruCost.hide();
            Elements.centruCost.hide();
        }
    };

    var setHasModifiedView = function() {
        isModified = true;
        if (!cerere)
            return;

        actionFirstBtn = buttonActions.Save;
        actionSecondBtn = buttonActions.Cancel;
        Elements.firstBtn.attr("value", translate('Cerere_Modificare'));
        Elements.secondBtn.attr("value", translate('Cerere_Renuntare'));
        setButtonsActions(buttonActions.ModifyCancel);
    };

    var renderEmployeeInfo = function(info, isLoading) {
        if (!info) {
            info = new Object();
            info.Name = translate('Cerere_SelectatiAngajat');
            info.FNC_NUME = translate('Cerere_SelectAngajatText');
            info.DPT_NUME = "";
            info.CNP = "";
            info.Marca = "";
            info.Poza = getImageUrl(Constants.genericEmployeePic);
        } else {
            info.DPT_NUME = translate('Cerere_Departament') + " " + info.DPT_NUME;
            info.CNP = translate('Cerere_CNP') + " " + info.CNP;
            info.Marca = translate('Cerere_Marca') + " " + info.Marca;

            if (info.HasPicture)
                info.Poza = Utils.getEmployeePhoto(info.PRS_ID);
            else info.Poza = Utils.defaultEmployeePhotoPath;
        }
        info.IsLoading = isLoading || false;

        Elements.angajatContainer.show();
        var html = Templates.userInfoTemplateCompiled(info);
        Elements.angajatContainer.html(html);

        setCanChooseEmployee(self.Rights.SchimbarePersoana);
    };

    var initializeDatepickers = function() {
        Utils.initializeDatePicker(Elements.dataStartInput, function() {
            var ds = Elements.dataStartInput.scroller('getDate');
            setDataStart(ds);
        });

        Utils.initializeDatePicker(Elements.dataSfarsitInput, function() {
            var ds = Elements.dataSfarsitInput.scroller('getDate');
            setDataSfarsit(ds);
        });

        Utils.initializeDatePicker(Elements.dataCurentaInput, function() {
            var ds = Elements.dataCurentaInput.scroller('getDate');
            setDataCurenta(ds);
        });

        Utils.initializeDatePicker(Elements.oraStartInput, function() {
            var ds = Elements.oraStartInput.scroller('getDate');
            setOraStart(ds, true);
        }, 'time');

        Utils.initializeDatePicker(Elements.oraSfarsitInput, function() {
            var ds = Elements.oraSfarsitInput.scroller('getDate');
            setOraSfarsit(ds, true);
        }, 'time');
    };

    var setOraStart = function(os, force) {
        if (!os)
            os = new Date();

        var td = oraStart && oraSfarsit ? Time.getTimeDifference(oraStart, oraSfarsit) : null;

        oraStart = os;

        Elements.oraStart.html(moment(os).format('HH:mm'));
        Elements.oraStartInput.scroller('setDate', oraStart, true);

        if (oraSfarsit) {
            var timeDiff = Time.getTimeDifference(oraStart, oraSfarsit);
            if ((oraStart >= oraSfarsit || timeDiff.H == 0) && force) {
                var osNew = new Date(oraStart.toString());
                if (osNew.getHours() < 23)
                    osNew = osNew.addHours(1);

                setOraSfarsit(osNew);
            } else {
                if (td && force) {
                    var osNew = new Date(oraStart.toString());
                    if (osNew.getHours() + td.H <= 23)
                        osNew = osNew.addHours(td.H);
                    setOraSfarsit(osNew);
                }
            }
        }

        updateNrZile();
    };

    var setOraSfarsit = function(os, force) {
        if (!os)
            os = new Date();

        oraSfarsit = os;

        Elements.oraSfarsit.html(moment(os).format('HH:mm'));
        Elements.oraSfarsitInput.scroller('setDate', oraSfarsit, true);

        if (oraStart) {
            var timeDiff = Time.getTimeDifference(oraStart, oraSfarsit);
            if ((oraStart >= oraSfarsit || timeDiff.H == 0) && force) {
                var osNew = new Date(oraSfarsit.toString());
                if (osNew.getHours() > 0)
                    osNew = osNew.addHours(-1);

                setOraStart(osNew);
            }
        }
        updateNrZile();
    };

    self.initialize = override(self.initialize, function() {
        self.Title = translate('Module_Title_AdaugareCerere');
        app.translatePage(app.Pages.Cerere);

        var source = Templates.userInfoTemplate.html();
        Templates.userInfoTemplateCompiled = Handlebars.compile(source);

        Elements.selectTipCerere.click(function(e) {
            chooseTipCerere();
            return Event.stopEvent(e);
        });

        initializeDatepickers();

        Elements.dataStart.click(function() {
            if (!self.Rights.SchimbareDataStart)
                return;

            Elements.dataStartInput.scroller('show');
        });

        Elements.dataCurenta.click(function() {
            if (!self.Rights.SchimbareDataStart)
                return;

            Elements.dataCurentaInput.scroller('show');
        });

        Elements.oraStart.click(function() {
            if (!self.Rights.SchimbareDataStart)
                return;

            Elements.oraStartInput.scroller('show');
        });

        Elements.oraSfarsit.click(function() {
            if (!self.Rights.SchimbareDataStart)
                return;

            Elements.oraSfarsitInput.scroller('show');
        });

        Elements.atasareDocument.click(function() {
            if (!self.Rights.IncarcareFisier)
                return;
            app.Phone.getPicture(translate('PhoneDialog_GetPicture_Title'), translate('PhoneDialog_GetPicture_Camera'), translate('PhoneDialog_GetPicture_Gallery'), translate('PhoneDialog_GetPicture_Cancel'));
        });

        Elements.dataSfarsit.click(function() {
            if (!self.Rights.SchimbareDataSfarsit || $(this).hasClass('disabled'))
                return;

            if (tipConcediu && tipConcediu.Subtip && tipConcediu.Subtip.STP_DATAFINALA_BLOCATA)
                return;

            if (cerere && cerere.CCD_ID && cerere.PoateModifica == 1)
                Elements.dataSfarsitInput.scroller('option', 'minDate', cerere.MinDate);
            else {
                if (!tipConcediu || !tipConcediu.Tip || !tipConcediu.Tip.IsHour)
                    Elements.dataSfarsitInput.scroller('option', 'minDate', null);
            }

            Elements.dataSfarsitInput.scroller('show');
        });

        Elements.firstBtn.click(function(e) {
            if (actionFirstBtn == buttonActions.Save)
                salvareCerere();
            else if (actionFirstBtn == buttonActions.Accept)
                aprobareCerere();
            return Event.stopEvent(e);
        });

        Elements.secondBtn.click(function(e) {
            if (actionSecondBtn == buttonActions.Cancel) {
                if (isModified && cerere)
                    setCerereData(cerere);
                else app.goBack();
            } else if (actionSecondBtn == buttonActions.Revoke)
                refuzareCerere();
            return Event.stopEvent(e);
        });

        Elements.centruCost.click(function(e) {
            if (app.TMMData.Setari.TipCentruCost == 0)
                chooseCentruCost();
            else chooseDimensiuni();

            return Event.stopEvent(e);
        });

        pageContainer.bind('onBeforePageShow', function() {
            app.Phone.setBackbtnVisible(!app.HasPageChangedFromMenu);
        });

        Elements.fisiereContainer.find('a.delete').on('click', function(e) {
            stergereFisier($(this).parent());
            return Event.stopEvent(e);
        });

        Elements.descriereCerereTextArea.autoGrow();
        Elements.descriereCerereTextArea.change(function() {
            setHasModifiedView();
        });

        Elements.descriereCerereTextArea.focus(function() {
            Utils.scrollParentIntoView(Elements.descriereCerereTextArea[0]);
        });

        Elements.replacementEmployeeName.click(function(e) {
            if (!self.Rights.SchimbareInlocuitor)
                return;

            chooseEmployee(function(response) {
                if (response)
                    setReplacementEmployee({
                        NUME: response.Name,
                        PRA_ID: response.PRA_ID
                    });
            });

            return Event.stopEvent(e);
        });
    });

    var stergereFisier = function(li) {
        var id = li.attr('did');

        app.MessagesFactory.showDialog(translate('General_Confirmare_Stergere'), translate('Cerere_StergereFisier'), [
            {
                Text: translate('General_Da'),
                Callback: function() {
                    for (var i = 0; i < cerere.Documents.length; i++) {
                        var d = cerere.Documents[i];
                        if (d.Id == id) {
                            d.Status = 2;
                            setFisiere();
                            break;
                        }
                    }
                    app.MessagesFactory.hideDialog();
                    if (!isModified)
                        setHasModifiedView();
                }
            },
            {
                Text: translate('General_Nu'),
                Callback: function() {
                    app.MessagesFactory.hideDialog();
                }
            }
        ]);
    };

    var chooseCentruCost = function() {
        if (!app.Pages.CentreCost.instance)
            app.Pages.CentreCost.instance = new CentreCostPage(app.Pages.CentreCost.container);
        app.changePage(app.Pages.CentreCost, true);

        app.Pages.SelectareDimensiuniStructuri.instance.setCallback(function(cc) {
            isModified = true;
            centruCost = cc;
            Elements.centruCost.html(translate('General_Completat'));
            app.changePage(app.Pages.Cerere);
        });

        app.Pages.CentreCost.instance.refresh();
    };

    var chooseDimensiuni = function() {
        if (!app.Pages.SelectareDimensiuniStructuriPage.instance)
            app.Pages.SelectareDimensiuniStructuriPage.instance = new SelectareDimensiuniStructuriPage(app.Pages.SelectareDimensiuniStructuriPage.container);
        app.changePage(app.Pages.SelectareDimensiuniStructuriPage, true);

        if (centruCost && centruCost.CC_NUME.length) {
            var editable = !cerere || (cerere && cerere.PoateModifica >= 1);
            app.Pages.SelectareDimensiuniStructuriPage.instance.setCentruCost(centruCost.CC_NUME, editable);
        }

        app.Pages.SelectareDimensiuniStructuriPage.instance.setCallback(function(structura) {
            if (structura) {
                isModified = true;
                centruCost = {
                    CC_ID: structura.Result.FinalResult.CC_ID,
                    CC_NUME: structura.Term
                };

                if (centruCost.CC_ID != 0)
                    Elements.centruCost.html(translate('General_Completat'));

                setHasModifiedView();
            }
            app.goBack();
        });
    };

    this.closePopups = override(self.closePopups, function() {
        Elements.dataStartInput.scroller('hide');
        Elements.dataSfarsitInput.scroller('hide');
    });

    var aprobareCerere = function() {
        if (!cerere || isModified || !self.Rights.Aprobare)
            return;

        app.showLoadingScreen();
        app.TMMService.Cereri.AprobaCerere(cerere.CCD_ID, function(response) {
            app.hideLoadingScreen();
            if (response.Exception)
                return app.MessagesFactory.showToastWarning(translate('General_Eroare'), translate('Cerere_Eroare_Aprobare'));

            $(document).trigger('CerereApproved');

            app.MessagesFactory.showDialog(translate('General_Succes'), translate('Cerere_Succes_Aprobare'), [
                {
                    Text: 'OK',
                    Callback: function() {
                        app.MessagesFactory.hideDialog();
                    }
                }
            ]);

            cerere.Status = 1;
            self.setCerere(cerere.CCD_ID);
            Event.sendEvent(null, Events.Cerere_Approved, { CCD_ID: cerere.CCD_ID });
        });
    };

    var refuzareCerere = function() {
        if (!cerere || isModified || !self.Rights.Refuzare)
            return;

        showMotivRefuzDialog(function(descriere) {
            if (!descriere || !descriere.length)
                return;

            app.showLoadingScreen();
            app.TMMService.Cereri.RefuzaCerere(cerere.CCD_ID, descriere, function(response) {
                app.hideLoadingScreen();
                if (response.Exception)
                    return app.MessagesFactory.showToastWarning(translate('General_Eroare'), translate('Cerere_Eroare_Refuzare'));

                $(document).trigger('CerereDenied');

                app.MessagesFactory.showDialog(translate('General_Succes'), translate('Cerere_Succes_Refuzare'), [
                    {
                        Text: 'OK',
                        Callback: function() {
                            app.MessagesFactory.hideDialog();
                        }
                    }
                ]);

                cerere.Status = 2;
                self.setCerere(cerere.CCD_ID);
                Event.sendEvent(null, Events.Cerere_Refused, { CCD_ID: cerere.CCD_ID });
            });
        });
    };

    var salvareCerere = function() {
        if (!self.Rights.Modificare)
            return;

        if (current_pra_id == -1)
            return app.MessagesFactory.showToastWarning(translate('Cerere_CampuriInvalide'), translate('Cerere_SelectAngajat'));

        if (!tipConcediu)
            return app.MessagesFactory.showToastWarning(translate('Cerere_CampuriInvalide'), translate('Cerere_SelectTipCO'));

        if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour) {

        } else if (!Elements.dataStartInput.val().length) {
            return app.MessagesFactory.showToastWarning(translate('Cerere_CampuriInvalide'), translate('Cerere_SelectDataStart'));
        }

        if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.NeedsReplacementEmployee) {
            if (!pra_id_inlocuitor)
                return app.MessagesFactory.showToastWarning(translate('Cerere_CampuriInvalide'), translate('Cerere_Error_SelectatiInlocuitor'));

            if (pra_id_inlocuitor == app.User.PRA_ID)
                return app.MessagesFactory.showToastWarning(translate('Cerere_CampuriInvalide'), translate('Cerere_Error_AltInlocuitor'));
        }

        if (app.TMMData.Setari.TipPontare == 1 && tipConcediu.Tip.TIP_CC && !centruCost)
            return app.MessagesFactory.showToastWarning(translate('Cerere_CampuriInvalide'), translate('Cerere_SelectCC'));

        if (cerere && cerere.CCD_ID && cerere.PoateModifica < 1) {
            if (cerere.PoateModifica >= 1)
                app.MessagesFactory.showToastInfo(translate('General_NicioModificare'));
            return;
        }
        if (!cerere)
            cerere = {};

        if (!cerere.CCD_ID) {
            salvareCerereCuDescriere(null);
        } else showMotivModificareDialog(function(motivModificare) { salvareCerereCuDescriere(motivModificare); });
    };

    var salvareCerereCuDescriere = function(motivModificare) {
        var ds = null;
        var de = null;

        if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour) {
            ds = Elements.dataCurentaInput.scroller('getDate');
            de = Elements.dataCurentaInput.scroller('getDate');

            ds.setHours(oraStart.getHours());
            ds.setMinutes(oraStart.getMinutes());

            de.setHours(oraSfarsit.getHours());
            de.setMinutes(oraSfarsit.getMinutes());
        } else {
            ds = Elements.dataStartInput.scroller('getDate');
            de = Elements.dataSfarsitInput.scroller('getDate');
            if (!ds || !de)
                return;
        }

        cerere.DataStart = ds.formatDateTime();
        cerere.DataSfarsit = de.formatDateTime();

        cerere.TCO_ID = tipConcediu.Tip.TCO_ID;
        cerere.ELM_ID = tipConcediu.Tip.ELM_ID;
        cerere.STP_ID = null;
        if (tipConcediu.Subtip)
            cerere.STP_ID = tipConcediu.Subtip.STP_ID;
        cerere.Descriere = Elements.descriereCerereTextArea.val();
        var cc_id = centruCost;
        if (centruCost && (centruCost.CC_ID || centruCost.CC_NUME))
            cc_id = centruCost.CC_ID;

        cerere.PRA_ID_INLOCUITOR = 0;
        if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.NeedsReplacementEmployee)
            cerere.PRA_ID_INLOCUITOR = pra_id_inlocuitor;

        var dimensiuni = centruCost && centruCost.CC_ID == -1 ? centruCost.CC_NUME : null;

        if (cerere.Documents) {
            var docs = new Array();
            for (var i = 0; i < cerere.Documents.length; i++) {
                var d = cerere.Documents[i];
                docs.push({
                    Id: d.Id,
                    Name: d.Name,
                    Description: d.Description || "",
                    Content: d.Content,
                    ContentString: d.ContentString,
                    DocumentSize: d.DocumentSize,
                    ServerPath: d.ServerPath,
                    Status: d.Status
                });
            }

            cerere.Documents = docs;

            for (var i = 0; i < cerere.Documents.length; i++) {
                var d = cerere.Documents[i];
                if (d.Status == 2) {
                    if (!d.Id) {
                        cerere.Documents.splice(i, 1);
                        i--;
                    }
                }
            }
        }

        var settings = app.getCurrentSettings();
        app.showLoadingScreen();
        app.TMMService.Cereri.SalvareCerere(cerere.CCD_ID, current_pra_id, cerere.DataStart, cerere.DataSfarsit, cerere.ELM_ID, cerere.TCO_ID, cerere.STP_ID, cerere.Descriere, cc_id, dimensiuni, settings.Language, cerere.Documents, motivModificare, cerere.PRA_ID_INLOCUITOR, function(response) {
            app.hideLoadingScreen();
            if (response.Exception) {
                if (response.Exception.Code)
                    app.MessagesFactory.showToastWarning(translate('General_Eroare'), response.Exception.Message);
                else app.MessagesFactory.showToastWarning(translate('General_Eroare'), translate('General_EroareServer'));
                return;
            }

            var isNew = cerere.CCD_ID;
            cerere.CCD_ID = response.FinalResult;
            self.setCerere(response.FinalResult);

            app.MessagesFactory.showDialog(translate('General_Succes'), translate('Cerere_Succes_Salvare'), [
                {
                    Text: 'OK',
                    Callback: function() {
                        app.MessagesFactory.hideDialog();
                    }
                }
            ]);

            if (isNew)
                Event.sendEvent(null, Events.Cerere_Added, { CCD_ID: cerere.CCD_ID });
            else Event.sendEvent(null, Events.Cerere_Modified, { CCD_ID: cerere.CCD_ID });
        });
    };

    var showMotivRefuzDialog = function(callback) {
        Elements.motivRefuzDialog.dialog({ 'templateId': Templates.refuzMotivTemplate.attr('id') });
        Elements.motivRefuzDialog.dialog('show', {
            Title: translate('Cerere_MotivRefuz'),
            Buttons: [
                {
                    Text: 'OK',
                    Callback: function() {
                        var descriere = Elements.motivRefuzDialog.find('textarea').val();
                        if (!descriere || !descriere.length)
                            return;

                        Elements.motivRefuzDialog.dialog('hide');
                        if (callback)
                            callback(descriere);
                    }
                },
                {
                    Text: 'Renuntare',
                    Callback: function() {
                        Elements.motivRefuzDialog.dialog('hide');
                        if (callback) callback();
                    }
                }
            ]
        });
        Elements.motivRefuzDialog.css('margin-top', '-145px');
        Elements.motivRefuzDialog.find('textarea').focus();
    };

    var showMotivModificareDialog = function(callback) {
        Elements.motivModificareDialog.dialog({ 'templateId': Templates.modificareMotivTemplate.attr('id') });
        Elements.motivModificareDialog.dialog('show', {
            Title: translate('Cerere_MotivModificare'),
            Buttons: [
                {
                    Text: 'OK',
                    Callback: function() {
                        var descriere = Elements.motivModificareDialog.find('textarea').val();
                        if (!descriere || !descriere.length) {
                            if (app.User.IsAlsoEmployee)
                                return app.MessagesFactory.showToastInfo(translate('General_Info'), translate('Cerere_MotivModificare_Obligatoriu'));
                        }

                        Elements.motivModificareDialog.dialog('hide');
                        if (callback)
                            callback(descriere);
                    }
                },
                {
                    Text: 'Renuntare',
                    Callback: function() { Elements.motivModificareDialog.dialog('hide'); }
                }
            ]
        });
        Elements.motivModificareDialog.css('margin-top', '-145px');
        Elements.motivModificareDialog.find('textarea').focus();
    };

    var setDataCurenta = function(ds, force) {
        if (ds == dataCurenta && !force)
            return;

        setHasModifiedView();
        dataCurenta = ds;
        if (!ds) {
            Elements.dataCurentaInput.scroller('setDate', new Date(), true);
            Elements.dataCurenta.html(translate('General_Selectati'));
        } else {
            Elements.dataCurentaInput.scroller('setDate', ds, true);
            Elements.dataCurenta.html(Globalize.format(ds, "d").toString());
        }

        if (cerere && (cerere.Status == 2 || cerere.Status == 3 || cerere.PoateModifica <= 1))
            Elements.dataCurenta.addClass('disabled');
        else Elements.dataCurenta.removeClass('disabled');

        updateNrZile();
    };

    var setDataStart = function(ds, force) {
        if (ds == dataStart && !force)
            return;

        setHasModifiedView();
        dataStart = ds;
        if (!ds) {
            Elements.dataStartInput.scroller('setDate', new Date(), true);
            Elements.dataStart.html(translate('General_Selectati'));
        } else {
            Elements.dataStartInput.scroller('setDate', ds, true);
            Elements.dataStart.html(Globalize.format(ds, "d").toString());
        }

        if (cerere && (cerere.Status == 2 || cerere.Status == 3 || cerere.PoateModifica <= 1))
            Elements.dataStart.addClass('disabled');
        else Elements.dataStart.removeClass('disabled');

        if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour) {
            if (!dataSfarsit || (dataSfarsit && dataSfarsit <= dataStart) || (dataSfarsit && (dataStart.getFullYear() != dataSfarsit.getFullYear() || dataStart.getMonth() != dataSfarsit.getMonth() || dataStart.getDate() != dataSfarsit.getDate()))) {
                if (!(ds.getHours() == 23 && ds.getMinutes() == 45)) {
                    var newDS = new Date(ds.toString());
                    newDS.setMinutes(newDS.getMinutes() + 15);
                    setDataSfarsit(newDS, true);
                } else setDataSfarsit(ds, true);
            } else updateNrZile();

            var startDateAllowed = new Date(ds.getFullYear(), ds.getMonth(), ds.getDate(), 0, 0, 0);
            var endDateAllowed = new Date(ds.getFullYear(), ds.getMonth(), ds.getDate(), 23, 45, 0);
            Elements.dataSfarsitInput.scroller('option', 'minDate', startDateAllowed);
            Elements.dataSfarsitInput.scroller('option', 'maxDate', endDateAllowed);
        } else {
            if (!dataSfarsit || (dataSfarsit && dataSfarsit < dataStart)) {
                setDataSfarsit(dataStart);
            }

            updateDataSfarsitSubtip();
            updateNrZile();
        }
    };

    var updateDataSfarsitSubtip = function() {
        if (tipConcediu && tipConcediu.Subtip && dataStart) {
            var nrZile = tipConcediu.Subtip.STP_ZILE || 0;
            var copiedDate = new Date(dataStart.getTime());
            if (nrZile)
                copiedDate = copiedDate.addDays(nrZile);
            setDataSfarsit(copiedDate);
        }
    };

    var setDataSfarsit = function(ds, force) {
        if (ds == dataSfarsit && !force)
            return;
        setHasModifiedView();
        dataSfarsit = ds;
        if (!ds) {
            Elements.dataSfarsitInput.scroller('setDate', new Date(), true);
            Elements.dataSfarsit.html(translate('General_Selectati'));
        } else {
            Elements.dataSfarsitInput.scroller('setDate', ds, true);
            Elements.dataSfarsit.html(Globalize.format(ds, "d").toString());
        }

        if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour) {
            if (!dataStart || (dataStart && dataStart > dataSfarsit)) {
                if (!(ds.getHours() == 0 && ds.getMinutes() == 0)) {
                    var newDS = new Date(ds.toString());
                    newDS.setMinutes(newDS.getMinutes() - 15);
                    setDataStart(newDS, true);
                } else setDataStart(ds, true);
            }
        } else {
            if (!dataStart || (dataStart && dataStart > dataSfarsit))
                setDataStart(dataSfarsit);
        }

        if (cerere && cerere.CCD_ID && (cerere.Status == 2 || cerere.Status == 3 || cerere.PoateModifica <= 1))
            Elements.dataSfarsit.addClass('disabled');
        else Elements.dataSfarsit.removeClass('disabled');

        updateNrZile();
    };

    var setReplacementEmployee = function(employee) {
        if (self.Rights.SchimbareInlocuitor)
            Elements.replacementEmployeeName.removeClass('disabled');
        else Elements.replacementEmployeeName.addClass('disabled');

        if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.NeedsReplacementEmployee)
            Elements.replacementEmployeeSection.show();
        else Elements.replacementEmployeeSection.hide();

        if (!employee) {
            Elements.replacementEmployeeName.html(translate('Cerere_SelectAngajat'));
            return;
        }

        pra_id_inlocuitor = employee.PRA_ID;

        Elements.replacementEmployeeName.html(employee.NUME);
    };
    this.savePicture = function(pic) {
        if (!cerere)
            cerere = {};

        if (!cerere.Documents)
            cerere.Documents = new Array();
        if (pic) {
            var name = translate('General_Fisier') + (cerere.Documents.length + 1) + "." + (Utils.getFileExtension(pic.name) || "unknown");
            var p = {
                Id: 0,
                Name: name,
                ContentString: pic.pic,
                Description: "",
                Status: 1
            };
            cerere.Documents.push(p);
            setFisiere();
            if (!isModified)
                setHasModifiedView();
        }
    };

    var updateNrZile = function() {
        if (!dataWasSet)
            return;

        if (tipConcediu && tipConcediu.Tip && tipConcediu.Tip.IsHour) {
            Elements.totalZileContainer.hide();

            var text = Utils.getTimeDifferenceText(oraStart, oraSfarsit);
            Elements.totalOreContainer.show().html(text);
        } else {
            if (!dataStart || !dataSfarsit) {
                Elements.totalZileContainer.find('span:first').show();
                Elements.totalZileContainer.find('span:eq(1)').hide();
                Elements.totalOreContainer.hide();
                return;
            }

            Elements.totalZileContainer.show();
            Elements.totalZileContainer.find('span:first').hide();
            Elements.totalZileContainer.find('span:eq(1)').show();

            var zileCalendaristice = Utils.getDateDiff(dataSfarsit, dataStart);
            Elements.nrZileCalendaristiceValue.html(zileCalendaristice);
            if (zileCalendaristice == 1)
                Elements.nrZileCalendaristice.html(translate('Cereri_ZiCalendaristica'));
            else Elements.nrZileCalendaristice.html(translate('Cereri_ZileCalendaristice'));

            if (current_pra_id) {
                var shiftSet = tipConcediu && !tipConcediu.Subtip && tipConcediu.Tip.ShiftSet;
                app.TMMService.Cereri.GetZileLucratoare(moment(dataStart).format('YYYY/MM/DD'), moment(dataSfarsit).format('YYYY/MM/DD'), current_pra_id, shiftSet, function(response) {
                    if (!response.Exception) {
                        Elements.nrZileLucratoareValue.html(response.FinalResult);
                        if (response.FinalResult == 1)
                            Elements.nrZileLucratoare.html(translate('Cereri_ZiLucratoare'));
                        else Elements.nrZileLucratoare.html(translate('Cereri_ZileLucratoare'));
                    }
                });
            } else {
                Elements.nrZileLucratoare.hide();
                Elements.nrZileLucratoareValue.hide();
            }
        }
    };

    var chooseTipCerere = function() {
        if (!self.Rights.SchimbareTipConcediu)
            return;

        if (!app.Pages.SelectareTipConcediu.instance)
            app.Pages.SelectareTipConcediu.instance = new SelectareTipConcediuPage(app.Pages.SelectareTipConcediu.container);
        app.Pages.SelectareTipConcediu.instance.setCallback(function(data) {
            self.setTipConcediu(data);
            app.changePage(app.Pages.Cerere);
        });
        app.changePage(app.Pages.SelectareTipConcediu, true);
    };

    this.setTipConcediu = function(data, force) {
        if (tipConcediu && data && !force) {
            if ((tipConcediu.Tip.TCO_ID && tipConcediu.Tip.TCO_ID == data.Tip.TCO_ID) || (tipConcediu.Tip.ELM_ID && tipConcediu.Tip.ELM_ID == data.Tip.ELM_ID)) {
                if (tipConcediu.Subtip && data.Subtip && tipConcediu.Subtip.STP_ID == data.Subtip.STP_ID)
                    return;
                else if (!tipConcediu.Subtip && !data.Subtip)
                    return;
            }
        }

        tipConcediu = data;
        setReplacementEmployee();
        setHasModifiedView();
        if (!data || !data.Tip) {
            Elements.selectTipCerere.html(translate('General_Selectati'));
            Elements.selectTipCerere.removeClass('disabled');

            Elements.dataCurentaInput.parents("p:first").hide();
            Elements.dataStartInput.parents("p:first").show();
            Elements.oraStartInput.parents("p:first").hide();
            Elements.totalOreContainer.hide();
            return;
        }

        if (data.Subtip) {
            isModified = true;
            Elements.selectTipCerere.html(data.Subtip.STP_NUME);
            Elements.titleSoldCO.parent().hide();
        } else {
            Elements.selectTipCerere.html(data.Tip.Nume);
            soldCO = -1;
            showSoldCO();
        }

        if (data.Tip && data.Tip.IsHour) {
            Elements.dataCurentaInput.parents("p:first").show();
            Elements.dataStartInput.parents("p:first").hide();
            Elements.oraStartInput.parents("p:first").show();
            Elements.totalOreContainer.show();

            if (!cerere || !cerere.CCD_ID) {
                if (!dataCurenta)
                    dataCurenta = new Date();

                if (!oraStart) {
                    oraStart = new Date();
                    if (oraStart.getMinutes() % 15 != 0)
                        oraStart = oraStart.addMinutes(15 - oraStart.getMinutes() % 15);
                }
                if (!oraSfarsit) {
                    oraSfarsit = new Date(oraStart.toString());
                    if (oraSfarsit.getMinutes() % 15 != 0)
                        oraSfarsit = oraSfarsit.addMinutes(15 - oraSfarsit.getMinutes() % 15);
                    if (oraSfarsit.getHours() < 23)
                        oraSfarsit = oraSfarsit.addHours(1);
                }

                setOraStart(oraStart);
                setOraSfarsit(oraSfarsit);
            }

            if (dataCurenta)
                setDataCurenta(dataCurenta, true);
        } else {
            Elements.dataCurentaInput.parents("p:first").hide();
            Elements.dataStartInput.parents("p:first").show();
            Elements.oraStartInput.parents("p:first").hide();
            Elements.totalOreContainer.hide();

            if (dataStart)
                setDataStart(dataStart, true);
            if (dataSfarsit)
                setDataSfarsit(dataSfarsit, true);
        }

        if (cerere && (cerere.Status == 2 || cerere.Status == 3 || cerere.PoateModifica <= 1)) {
            Elements.selectTipCerere.addClass('disabled');
            Elements.replacementEmployeeName.addClass('disabled');
        } else {
            Elements.selectTipCerere.removeClass('disabled');
            Elements.replacementEmployeeName.removeClass('disabled');
        }

        showCentruCost();
    };

    var chooseEmployee = function(callback) {
        if (!app.Pages.EmployeesList.instance)
            app.Pages.EmployeesList.instance = new EmployeesListPage(app.Pages.EmployeesList.container, 1);

        app.Pages.EmployeesList.instance.LoadType = app.Pages.EmployeesList.instance.LoadTypes.All;
        app.Pages.EmployeesList.instance.setSelectionCallback(function(response) {
            app.changePage(app.Pages.Cerere, true);
            app.Pages.EmployeesList.instance.setSelectionCallback(null);
            app.Pages.EmployeesList.instance.LoadType = app.Pages.EmployeesList.instance.LoadTypes.Subordinates;

            if (callback) {
                callback(response);
                return;
            }

            if (response) {
                loadUserInfo(response.PRA_ID);
                self.LastPageHash = null;
            }
        });

        app.changePage(app.Pages.EmployeesList, true);
        app.Pages.EmployeesList.instance.refresh();
    };

    var showSoldCO = function() {
        if (!current_pra_id || !tipConcediu || tipConcediu.Tip.TCO_ID != app.TMMData.ConcediuOdihna.TCO_ID) {
            Elements.titleSoldCO.parent().hide();
            return;
        }
        if (soldCO == -1)
            app.TMMService.TMM.GetSoldCO(new Date().getFullYear(), current_pra_id, function(response) {
                if (response.Exception)
                    return;

                setSoldCO(response.FinalResult);
            });
        else setSoldCO(soldCO);
    };

    var setSoldCO = function(sold) {
        soldCO = sold;

        var text = soldCO + " " + (soldCO == 1 ? translate('General_Zi').toLowerCase() : translate('General_Zile').toLowerCase());
        Elements.soldCO.html(text);
        Elements.titleSoldCO.parent().show();
    };

    var showIstoricCerere = function() {
        if (!cerere)
            return;

        if (!app.Pages.IstoricCerere.instance)
            app.Pages.IstoricCerere.instance = new IstoricCererePage(app.Pages.IstoricCerere.container);

        app.changePage(app.Pages.IstoricCerere);
        app.Pages.IstoricCerere.instance.CCD_ID = cerere.CCD_ID;
        app.Pages.IstoricCerere.instance.getPullUpData();
    };

    var stergereCerere = function() {
        if (!self.Rights.Stergere)
            return;

        app.MessagesFactory.showDialog(translate('General_Confirmare_Stergere'), translate('Cerere_Stergere_Confirmare'), [
            {
                Text: translate('General_Da'),
                Callback: function() {
                    app.showLoadingScreen();
                    app.TMMService.Cereri.StergeCerere(cerere.CCD_ID, function(response) {
                        app.hideLoadingScreen();
                        if (response.Exception)
                            return app.MessagesFactory.showToastWarning(translate('General_Eroare'), translate('General_EroareServer'));

                        Event.sendEvent(null, Events.Cerere_Deleted, { CCD_ID: cerere.CCD_ID });

                        if (!app.Pages.CereriConcedii.instance) {
                            app.Pages.CereriConcedii.instance = new CereriConcediiPage(app.Pages.CereriConcedii.container);
                            app.Pages.CereriConcedii.instance.initialize();
                            app.Pages.CereriConcedii.instance.refresh();
                        }
                        app.changePage(app.Pages.CereriConcedii);
                    });
                    app.MessagesFactory.hideDialog();
                }
            },
            {
                Text: translate('General_Nu'),
                Callback: function() {
                    app.MessagesFactory.hideDialog();
                }
            }
        ]);
    };

    var setCanChooseEmployee = function(visible) {
        if (visible) {
            if (!Elements.angajatContainer.find(".cc-name-big-change-employee").length)
                Elements.angajatContainer.find(".userName").addClass("cc-name-big-change-employee");
            Elements.angajatContainer.find(".changeEmployee").show();
        } else {
            Elements.angajatContainer.find(".userName").removeClass("cc-name-big-change-employee");
            Elements.angajatContainer.find(".changeEmployee").hide();
        }
    };

    var setButtonsActions = function(action) {
        if (action == buttonActions.AcceptRevoke) {
            actionFirstBtn = buttonActions.Accept;
            actionSecondBtn = buttonActions.Revoke;
            Elements.firstBtn.html(translate('Cerere_Aprobare')).show();
            Elements.secondBtn.html(translate('Cerere_Refuzare')).show();
            if (Elements.secondBtn.hasClass("but-grey"))
                Elements.secondBtn.removeClass("but-grey");
            if (!Elements.secondBtn.hasClass("but-red"))
                Elements.secondBtn.addClass("but-red");
        } else if (action == buttonActions.None) {
            Elements.firstBtn.hide();
            Elements.secondBtn.hide();
        } else {
            actionFirstBtn = buttonActions.Save;
            actionSecondBtn = buttonActions.Cancel;
            if (Elements.secondBtn.hasClass("but-red"))
                Elements.secondBtn.removeClass("but-red");
            Elements.secondBtn.html(translate('Cerere_Renuntare')).show();

            if (action == buttonActions.SaveCancel) {
                Elements.firstBtn.html(translate('Cerere_Adaugare')).show();
                if (Elements.secondBtn.hasClass("but-grey"))
                    Elements.secondBtn.removeClass("but-grey");
            } else if (action == buttonActions.ModifyCancel) {
                Elements.firstBtn.html(translate('Cerere_Modificare')).show();
                if (!Elements.secondBtn.hasClass("but-grey"))
                    Elements.secondBtn.addClass("but-grey");
            };
        }
    };

    this.setModuleAction = override(self.setModuleAction, function() {
        if (app.Phone)
            app.Phone.setModuleAction(cerere ? ModuleActions.More : ModuleActions.None);
    });

    this.goBack = function() {
        if (Elements.dataStartInput.attr("visible") == 'visible')
            return Elements.dataStartInput.scroller('hide');
        if (Elements.dataSfarsitInput.attr("visible") == 'visible')
            return Elements.dataSfarsitInput.scroller('hide');
        if (Elements.motivRefuzDialog.is(":visible"))
            return Elements.motivRefuzDialog.dialog('hide');
        if (Elements.motivModificareDialog.is(":visible"))
            return Elements.motivModificareDialog.dialog('hide');

        self.canLeave(function(can) {
            if (can) {
                if (self.LastPageHash)
                    app.changePage(app.getPageByHash(self.LastPageHash), true);
                else app.changePage(app.Pages.Dashboard, true);
            }
        });
    };

    this.canLeave = function(callback) {
        if (!isModified) {
            if (callback)
                callback(true);
            return;
        }

        app.MessagesFactory.showDialog(translate('General_Confirmare_ParasirePagina'), translate('Cerere_Confirmare_ParasirePagina_Text'), [
            {
                Text: translate('General_Da'),
                Callback: function() {
                    if (callback)
                        callback(true);
                    app.MessagesFactory.hideDialog();
                }
            },
            {
                Text: translate('General_Nu'),
                Callback: function() {
                    if (callback)
                        callback(false);
                    app.MessagesFactory.hideDialog();
                }
            }
        ]);
    };

    this.isAnyDialogOpen = override(self.isAnyDialogOpen, function() {
        if (Elements.dataStartInput.attr("visible") == 'visible')
            return true;
        if (Elements.dataSfarsitInput.attr("visible") == 'visible')
            return true;
        if (Elements.motivRefuzDialog.is(":visible"))
            return true;
        if (Elements.motivModificareDialog.is(":visible"))
            return true;

        return false;
    });

    this.hideAllDialogs = override(self.hideAllDialogs, function() {
        if (Elements.dataStartInput.attr("visible") == 'visible')
            Elements.dataStartInput.scroller('hide');
        if (Elements.dataSfarsitInput.attr("visible") == 'visible')
            Elements.dataSfarsitInput.scroller('hide');
        if (Elements.motivRefuzDialog.is(":visible"))
            Elements.motivRefuzDialog.dialog('hide');
        if (Elements.motivModificareDialog.is(":visible"))
            Elements.motivModificareDialog.dialog('hide');
    });

    self.initialize();
};
extend(CererePage, TMMobilePage);